import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  DatePicker,
  Form,
  Image,
  Input,
  Modal,
  Space,
  Table,
  Tag,
  Upload,
  message,
  ConfigProvider,
  Select,
  Popover,
  Empty,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { UploadFile } from 'antd/es/upload/interface';
import dayjs from 'dayjs';
import React, { useState, useEffect } from 'react';
import { getMilestonePage, addMilestone as addMilestoneService, updateMilestone as updateMilestoneService, deleteMilestone as deleteMilestoneService, Milestone } from '@/services/MilestoneService';
import { uploadFile } from '@/services/FileService';
import styles from './index.less';
import zhCN from 'antd/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import { famousPersonId } from '@/services';
import { FileDetail } from '@/services/index';
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const MilestoneAdmin: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [imageList, setImageList] = useState<UploadFile[]>([]);
  const [videoList, setVideoList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Milestone[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [videoModalVisible, setVideoModalVisible] = useState(false);
  const [currentVideo, setCurrentVideo] = useState('');
  const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [currentImagePage, setCurrentImagePage] = useState(1);

  // 添加数据加载函数
  const loadData = async (
    page = pagination.current,
    pageSize = pagination.pageSize,
    order = sortOrder
  ) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      console.log(values)
      const data = await getMilestonePage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        description: values.keyword,
        startDate: values.dateRange?.[0]?.format('YYYY-MM-DD'),
        endDate: values.dateRange?.[1]?.format('YYYY-MM-DD'),
        order: order,
      });

      setData(data.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: data.totalCount,
      });
      setSortOrder(order)
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 在组件加载时获取数据
  useEffect(() => {
    loadData();
  }, []);

  // 处理搜索
  const handleSearch = () => {
    loadData(1, 20);  // 搜索时重置到第一页
  };

  // 处理重置
  const handleReset = () => {
    searchForm.resetFields();
    loadData(1, 20, 'desc');  // 重置时回到第一页
  };

  // 处理取消
  const handleCancel = () => {
    setVisible(false);
    setEditingId(null);
    form.resetFields();
    setImageList([]);
    setVideoList([]);
  };

  // 处理编辑
  const handleEdit = (record: Milestone) => {
    setEditingId(record.id?.toString() || '');
    form.setFieldsValue({
      eventDate: dayjs(record.eventDate),
      description: record.description,
    });

    // 设置图片列表 - 添加空值检查
    setImageList(record.imageObjs?.map(file => ({
      uid: file.id.toString(),
      name: file.fileName,
      status: 'done',
      url: `/api/file/play/${file.id}`
    })) || []);  // 如果为空则设置为空数组

    // 设置视频列表 - 添加空值检查
    setVideoList(record.videoObjs?.map(file => ({
      uid: file.id.toString(),
      name: file.fileName,
      status: 'done',
      url: `/api/file/play/${file.id}`
    })) || []);  // 如果为空则设置为空数组

    setVisible(true);
  };



  // 处理文件上传
  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      // 直接获取返回的文件ID
      const fileId = await uploadFile(file);
      if (fileId) {
        // 上传成功，使用返回的文件ID更新文件列表
        onSuccess({
          uid: fileId.toString(),
          name: file.name,
          status: 'done',
          url: `/api/file/play/${fileId}`,
        });
      } else {
        onError(new Error('上传失败'));
        message.error('文件上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
      message.error('文件上传失败');
    }
  };

  // 处理删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条里程碑记录吗？',
      onOk: async () => {
        try {
          await deleteMilestoneService([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 理表单提交
  const handleSubmit = async (values: any) => {
    console.log(imageList)
    console.log(videoList)
    try {
      const submitData: Milestone = {
        id: editingId ? Number(editingId) : undefined,
        eventDate: values.eventDate.format('YYYY-MM-DD'),
        description: values.description,
        imageObjs: imageList.map(file => ({
          id: Number(file.response?.uid || file.uid),
          fileName: file.name
        })),
        videoObjs: videoList.map(file => ({
          id: Number(file.response?.uid || file.uid),
          fileName: file.name
        })),
        famousPersonId: famousPersonId,
      };

      if (editingId) {
        await updateMilestoneService(submitData);
        message.success('更新成功');
      } else {
        await addMilestoneService(submitData);
        message.success('添加成功');
      }

      handleCancel();
      loadData();
    } catch (error) {
      message.error(editingId ? '更新失败' : '添加失败');
    }
  };

  // 处理图片预览
  const handlePreview = async (file: UploadFile) => {
    const resp = file.response
    if (resp) {
      const fileId = resp.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const fileId = file.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    }
  };

  // 修改图片预览部分
  const renderImagePreview = (imageObjs: FileDetail[]) => {
    if (!imageObjs || imageObjs.length === 0) {
      return <Tag color="default">无图片</Tag>;
    }

    const pageSize = 6; // 每页显示6张图片
    const totalPages = Math.ceil(imageObjs.length / pageSize);

    const PopoverContent = () => {
      const startIndex = (currentImagePage - 1) * pageSize;
      const currentImages = imageObjs.slice(startIndex, startIndex + pageSize);

      return (
        <div className={styles.imageListContainer}>
          <div className={styles.imageList}>
            <Image.PreviewGroup>
              {currentImages.map((file) => (
                <div key={file.id} className={styles.imageItem}>
                  <Image
                    src={`/api/file/play/${file.id}`}
                    alt={file.fileName}
                    width={120}
                    height={120}
                    style={{ objectFit: 'cover', borderRadius: 4 }}
                    preview={{
                      mask: '预览',
                      maskClassName: styles.previewMask,
                    }}
                  />
                </div>
              ))}
            </Image.PreviewGroup>
          </div>
          {totalPages > 1 && (
            <div className={styles.pagination}>
              <Button
                size="small"
                disabled={currentImagePage === 1}
                onClick={() => setCurrentImagePage(prev => prev - 1)}
              >
                上一页
              </Button>
              <span className={styles.pageInfo}>
                {currentImagePage}/{totalPages}
              </span>
              <Button
                size="small"
                disabled={currentImagePage === totalPages}
                onClick={() => setCurrentImagePage(prev => prev + 1)}
              >
                下一页
              </Button>
            </div>
          )}
        </div>
      );
    };

    return (
      <div className={styles.imagePreview}>
        <Popover
          content={<PopoverContent />}
          title="图片列表"
          trigger="hover"
          placement="right"
          onOpenChange={(visible) => {
            if (visible) {
              setCurrentImagePage(1); // 每次打开时重置到第一页
            }
          }}
        >
          <Tag color="processing" style={{ cursor: 'pointer' }}>
            {imageObjs.length} 张图片
          </Tag>
        </Popover>
      </div>
    );
  };

  // 修改视频预览部分的渲染
  const renderVideoPreview = (videoObjs: FileDetail[]) => {
    if (!videoObjs || videoObjs.length === 0) {
      return <Tag color="default">无视频</Tag>;
    }

    return (
      <div className={styles.videoPreview}>
        <Popover
          content={
            <div className={styles.videoList}>
              {videoObjs.map((file) => (
                <div key={file.id} className={styles.videoItem}>
                  <Button
                    type="link"
                    onClick={() => handleVideoClick(file.id)}
                    style={{ padding: 0 }}
                  >
                    {file.fileName}
                  </Button>
                </div>
              ))}
            </div>
          }
          title="视频列表"
          trigger="hover"
        >
          <Tag color="processing">
            {videoObjs.length} 个视频
          </Tag>
        </Popover>
      </div>
    );
  };

  // 表格列定义
  const columns: ColumnsType<Milestone> = [
    {
      title: '日期',
      dataIndex: 'eventDate',
      key: 'eventDate',
      width: 110,
    },
    {
      title: '事件描述',
      dataIndex: 'description',
      key: 'description',
      width: '45%',  // 增加描述区域宽度
      ellipsis: true,
    },
    {
      title: '图片',
      dataIndex: 'imageObjs',
      key: 'imageObjs',
      width: 200,  // 减小图片区域宽度
      render: renderImagePreview,
    },
    {
      title: '视频',
      dataIndex: 'videoObjs',
      key: 'videoObjs',
      width: 150,
      render: renderVideoPreview,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,  // 减小操作列宽度
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索表单渲染
  const renderSearchForm = () => (
    <Form form={searchForm} layout="inline" className={styles.searchForm}>
      <Form.Item name="dateRange">
        <RangePicker
          placeholder={['开始日期', '结束日期']}
          allowClear
        />
      </Form.Item>
      <Form.Item name="keyword">
        <Input
          placeholder="搜索事件描述"
          prefix={<SearchOutlined />}
          allowClear
          onPressEnter={handleSearch}
        />
      </Form.Item>
      <Form.Item label="时间排序">
        <Select
          value={sortOrder}
          onChange={(value) => {
            // setSortOrder(value);
            loadData(1, pagination.pageSize, value); // 切换排序时重新加载第一页
          }}
          style={{ width: 120 }}
        >
          <Select.Option value="desc">从新到旧</Select.Option>
          <Select.Option value="asc">从旧到新</Select.Option>
        </Select>
      </Form.Item>
      <Form.Item>
        <Space>
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </Form.Item>
      <Form.Item>
        {/* 放到最右边 */}
        <Space style={{ marginLeft: 20 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setVisible(true)}
          >
            添加里程碑
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );

  // 修改分页器变化处理函数
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    }));
    loadData(newPagination.current, newPagination.pageSize);
  };

  // 添加处理视频点击的函数
  const handleVideoClick = (videoId: string) => {
    setCurrentVideo(`/api/file/play/${videoId}`);
    setVideoModalVisible(true);
  };

  // 添加处理模态框关闭的函数
  const handleModalClose = () => {
    if (videoRef) {
      videoRef.pause();  // 暂停视频
      videoRef.currentTime = 0;  // 重置视频时间
    }
    setVideoModalVisible(false);
  };

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <Card
          title="里程碑管理"
        >
          {renderSearchForm()}
          <Table
            columns={columns}
            dataSource={data}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            rowKey="id"
            className={styles.table}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ['20', '50', '100'],
            }}
            loading={loading}
            locale={{
              emptyText: (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description="暂无数据"
                />
              )
            }}
            onChange={handleTableChange}
          />
        </Card>

        <Modal
          title={editingId ? '编辑里程碑' : '添加里程碑'}
          open={visible}
          onCancel={handleCancel}
          footer={null}
          width={800}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              label="日期"
              name="eventDate"
              rules={[{ required: true, message: '请选择日期' }]}
            >
              <DatePicker
                style={{ width: '100%' }}
              />
            </Form.Item>

            <Form.Item
              label="事件描述"
              name="description"
              rules={[{ required: true, message: '请输入事件描述' }]}
            >
              <TextArea rows={4} maxLength={1000} showCount />
            </Form.Item>

            <Form.Item label="图片">
              <Upload
                listType="picture-card"
                fileList={imageList}
                onChange={({ fileList }) => setImageList(fileList)}
                customRequest={handleUpload}
                multiple
                accept="image/*"
                maxCount={15}  // 修改为15张
                onRemove={(file) => {
                  const newFileList = imageList.filter(item => item.uid !== file.uid);
                  setImageList(newFileList);
                  return true;
                }}
                onPreview={handlePreview}
              >
                {imageList.length >= 15 ? null : (  // 修改判断条件
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传图片</div>
                  </div>
                )}
              </Upload>
            </Form.Item>

            <Form.Item
              label="视频"
              style={{ marginBottom: 24 }}
            >
              <Upload
                fileList={videoList}
                onChange={({ fileList }) => setVideoList(fileList)}
                customRequest={handleUpload}
                multiple
                accept="video/*"
                maxCount={5}  // 添加最大数量限制
                onRemove={(file) => {
                  const newFileList = videoList.filter(item => item.uid !== file.uid);
                  setVideoList(newFileList);
                  return true;
                }}
              >
                {videoList.length >= 5 ? null : (  // 添加判断条件
                  <Button icon={<UploadOutlined />}>上传视频</Button>
                )}
              </Upload>
            </Form.Item>

            <Form.Item className={styles.modalFooter}>
              <Space>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 添加视频播放模态框 */}
        <Modal
          title="视频播放"
          open={videoModalVisible}
          onCancel={handleModalClose}
          footer={null}
          width={800}
          centered
          destroyOnClose
        >
          <video
            ref={(ref) => setVideoRef(ref)}
            src={currentVideo}
            controls
            style={{ width: '100%' }}
            autoPlay
          />
        </Modal>

        {/* 添加预览组件 */}
        {previewImage && (
          <Image
            style={{ display: 'none' }}
            preview={{
              visible: previewOpen,
              src: previewImage,
              onVisibleChange: (visible) => {
                setPreviewOpen(visible);
                if (!visible) {
                  setPreviewImage('');
                }
              },
            }}
          />
        )}
      </div>
    </ConfigProvider>
  );
};

export default MilestoneAdmin;
